package com.yulang.security.provider;

import com.yulang.security.mobile.MobileAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class MobileAuthProvider implements AuthenticationProvider {


    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 认证处理 通过手机号码查询用户信息 查询应该交给 userDetailsService 当查询到用户信息 封装user对象
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String mobile = authentication.getPrincipal().toString();

        // 通过手机号码查询用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        if(userDetails==null) {
            throw new AuthenticationServiceException("为查询到用户信息");
        }
        // 封装数据
        MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        mobileAuthenticationToken.setDetails(authentication.getDetails());
        return mobileAuthenticationToken;
    }

    /**
     * 主要通过这个方法选择相应的provider 返回true就是支持
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return MobileAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
